package com.ssy.invoicing.order.comtroller;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ssy.invoicing.common.controller.BaseController;
import com.ssy.invoicing.common.util.FileUtil;
import com.ssy.invoicing.dao.support.BaseSqlDao.SplitPageResult;
import com.ssy.invoicing.order.bean.PurchaseOrderBean;
import com.ssy.invoicing.order.bean.PurchaseProductBean;
import com.ssy.invoicing.order.bean.SaleOrderBean;
import com.ssy.invoicing.order.bean.vo.OrderVo;
import com.ssy.invoicing.order.service.OrderService;
import com.ssy.invoicing.order.service.PurchaseService;
import com.ssy.invoicing.suppliers.bean.SuppliersBean;
import com.ssy.invoicing.suppliers.service.SuppliersService;

/**
 * 采购订单Controller Comment of PurchaseController
 * @author suoyao.shen
 */
@Controller
@RequestMapping("invoicing")
public class PurchaseController extends BaseController {
    Logger logger = LoggerFactory.getLogger(PurchaseController.class);

    @Resource(name = "purchaseService")
    private PurchaseService purchaseService;
    
    @Resource(name="orderService")
    private OrderService orderService;
    
    @Resource(name="suppliersService")
    private SuppliersService suppliersService;

    /**
     * @param model
     * @return
     */
    @RequestMapping("addPurchase")
    public ModelAndView addPurchase(OrderVo vo,ModelMap model) {
        if (vo.getBeginTime() == null && vo.getEndTime() == null) {
            return new ModelAndView("pages/purchase/add");
        }
        //获取销售订单列表
        try {
            List<SaleOrderBean> orderList = orderService.queryOrderListNoPurchase(vo);
            model.put("orderList", orderList);
            model.put("vo", vo);
            //获得供应商
            List<SuppliersBean> suppliersList = suppliersService.querySuppliersList();
            model.put("suppliersList", suppliersList);
        } catch (SQLException e) {
            logger.error("query customer list fail.",e);
            return new ModelAndView("pages/purchase/add");
        }
        return new ModelAndView("pages/purchase/add");
    }

    /**
     * @param orderNumber
     * @param saleCount
     * @param salePrice
     * @param totalPrice
     * @param deliverTime
     * @param suppliers
     * @param remark
     * @param productId
     * @param model
     * @return
     */
    @RequestMapping("savePurchase")
    public ModelAndView savePurchase(String orderId, String orderNumber, String[] pname, String[] pattern,
                                     Integer[] saleCount, String[] salePrice, String[] totalPrice,
                                     Date[] deliverTime, String[] suppliers, String[] remark,
                                     Integer[] productId, ModelMap model) {
        if (productId == null || productId.length <= 0) {
            // 没有新增任何采购订单
            model.put("message", "没有要添加的产品项次");
            return new ModelAndView("pages/purchase/add");
        }
        purchaseService.savePurchaseBatch(orderId, orderNumber,pname,pattern, saleCount, salePrice, totalPrice,
                deliverTime, suppliers, remark, productId);
        model.put("message", "创建采购订单成功");
        return new ModelAndView("pages/purchase/add");
    }
    
    /**
     * @param vo
     * @param model
     * @return
     */
    @RequestMapping("listPurchase")
    public ModelAndView listPurchase(OrderVo vo,ModelMap model) {
        try {
            SplitPageResult spr = purchaseService.queryPurchaseList(vo);
            model.put("pagination", spr.getPagination());
            model.put("purchaseList", spr == null ? null : spr.getResult());
            model.put("vo", vo);
        } catch (SQLException e) {
            logger.error("query Purchase list fail.",e);
            return new ModelAndView("pages/error/err");
        }
        return new ModelAndView("pages/purchase/list");
    }
    
    @RequestMapping("detailPurchase")
    public ModelAndView detailPurchase(OrderVo vo, Integer purchaseId, ModelMap model) {
        /*
         * 获取采购订单信息 
         */
        PurchaseOrderBean purchase = purchaseService.getPurchaseById(purchaseId);
        /*
         * 获取采购订单下面的产品信息
         */
        List<PurchaseProductBean> productList = purchaseService.loadProductByPurchaseId(purchaseId);
        if(productList != null && productList.size() > 0) {
            //这里循环产品列表,汇总产品数量和价格
            int count = 0;
            long price = 0l;
            for (PurchaseProductBean product : productList) {
                count += product.getSaleCount().intValue();
                price += Long.valueOf(product.getTotalPrice());
            }
            PurchaseProductBean p = new PurchaseProductBean();
            p.setPname("汇总");
            p.setSaleCount(count);
            p.setTotalPrice(String.valueOf(price));
            productList.add(p);
        }
        model.put("purchase", purchase);
        model.put("productList", productList);
        model.put("vo", vo);
        return new ModelAndView("pages/purchase/detail");
    }
    
    /**
     * @param id
     * @return
     */
    @RequestMapping("removePurchase")
    public ModelAndView removePurchase(Integer id) {
        purchaseService.removePurchase(id);
        return new ModelAndView("redirect:listPurchase.htm");
    }
    
    /**
     * 查询列表并生成PDF文件
     * @author suoyao.shen
     * @param request
     * @param response
     * @param vo
     */
    @RequestMapping("downloadPDF")
    public void downloadPDF(Integer purchaseId,HttpServletRequest request, HttpServletResponse response) {
        File pdfFile = null;
        try {
            //生成PDF文件
            pdfFile = purchaseService.generatePDF(purchaseId);
            if (pdfFile == null) {
                return ;
            }
            FileUtil.writeDownloadFile("MSF公司采购订单.pdf", pdfFile, request, response);
        } catch (Exception e) {
            logger.error("download pdf file failed.");
        } finally {
            if (pdfFile != null && pdfFile.exists()) {
                try {
                    File delFile = new File(pdfFile.getParent());
                    FileUtils.forceDelete(delFile);
                } catch (IOException e) {
                    logger.error("delete pdf file error: ", e);
                }
            }
        }
    }
    
    /**
     * 生成Excel文件
     * @param purchaseId
     * @param request
     * @param response
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(Integer purchaseId,HttpServletRequest request, HttpServletResponse response) {
        File excelFile = null;
        try {
            //生成PDF文件
            excelFile = purchaseService.generateExcel(purchaseId);
            if (excelFile == null) {
                return ;
            }
            FileUtil.writeDownloadFile("MSF公司采购订单.xls", excelFile, request, response);
        } catch (Exception e) {
            logger.error("download pdf file failed.");
        } finally {
            if (excelFile != null && excelFile.exists()) {
                try {
                    File delFile = new File(excelFile.getParent());
                    FileUtils.forceDelete(delFile);
                } catch (IOException e) {
                    logger.error("delete pdf file error: ", e);
                }
            }
        }
    }
    
    /**
     * 转到修改采购订单产品信息页面
     * @param purchaseId
     * @param model
     * @return
     */
    @RequestMapping("editPurchaseProduct")
    public ModelAndView editPurchaseProduct(Integer purchaseId, ModelMap model) {
        PurchaseOrderBean purchase = purchaseService.getPurchaseById(purchaseId);
        List<PurchaseProductBean> productList = purchaseService.loadProductByPurchaseId(purchaseId);
        //获得供应商
        List<SuppliersBean> suppliersList = suppliersService.querySuppliersList();
        model.put("suppliersList", suppliersList);
        model.put("productList", productList);
        model.put("purchase", purchase);
        return new ModelAndView("pages/purchase/additional");
    }
    
    /**
     * 重新修改采购订单的产品信息
     * @param purchaseId
     * @param pname
     * @param pattern
     * @param saleCount
     * @param salePrice
     * @param totalPrice
     * @param deliverTime
     * @param suppliers
     * @param remark
     * @param model
     * @return
     */
    @RequestMapping("saveAdditionalPurchase")
    public ModelAndView saveAdditionalPurchase(String orderNumber,Integer purchaseId, String[] pname, String[] pattern,
                                               Integer[] saleCount, String[] salePrice,
                                               String[] totalPrice, Date[] deliverTime,
                                               String[] suppliers, String[] remark, ModelMap model) {
        purchaseService.saveAdditionalPurchase(orderNumber, purchaseId, pname, pattern, saleCount,
                salePrice, totalPrice, deliverTime, suppliers, remark);
        return new ModelAndView("redirect:detailPurchase.htm?purchaseId=" + purchaseId);
    }
    
}
